<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="header-container">
          <h3>考生列表</h3>
          <div class="button-group">
            <el-button type="primary" @click="handleRandom">随机列表</el-button>
            <el-button type="primary" @click="handleReorder">重新排序</el-button>
          </div>
        </div>
        
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="id" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="sex" label="性别" />
          <el-table-column prop="email" label="email" />
        </el-table>
      </el-col>
      <el-col :span="12">
        <rawDisplayer :value="tableData" title="列表内容" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import rawDisplayer from "@/components/infra/raw-displayer";
import { ref } from "vue";

import { generateRandomCandidates, reorderCandidates } from '@/api/candidates'

const originalData = ref([])
const tableData = ref([])

const handleRandom = async () => {
  try {
    const { data } = await generateRandomCandidates()
    originalData.value = [...data]  // 保存原始数据
    tableData.value = data
  } catch (error) {
    console.error('生成考生失败', error)
  }
}

const handleReorder = async () => {
  if (originalData.value.length === 0) {
    console.warn('请先生成随机列表')
    return
  }
  
  try {
    // 始终使用原始数据进行排序
    const { data } = await reorderCandidates(originalData.value)
    tableData.value = data
  } catch (error) {
    console.error('重新排序失败', error)
  }
}
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center;
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  gap: 10px;  /* 按钮间距 */
}

/* 可选：如果希望标题和按钮组之间有更大的间距 */
.header-container h3 {
  margin-right: 20px;
}
</style>